"""
响应格式化中间件 - 统一API响应格式
"""

from typing import Any, Optional, Dict
from dataclasses import dataclass
from flask import jsonify


@dataclass
class APIResponse:
    """统一的API响应格式"""
    success: bool
    message: str
    data: Optional[Any] = None
    error_code: Optional[str] = None
    timestamp: Optional[str] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        result = {
            "success": self.success,
            "message": self.message
        }
        
        if self.data is not None:
            result["data"] = self.data
            
        if self.error_code:
            result["error_code"] = self.error_code
            
        if self.timestamp:
            result["timestamp"] = self.timestamp
            
        return result
    
    def to_json_response(self, status_code: int = 200):
        """转换为Flask JSON响应"""
        return jsonify(self.to_dict()), status_code


class ResponseFormatter:
    """响应格式化工具类"""
    
    @staticmethod
    def success(message: str = "操作成功", data: Any = None, status_code: int = 200):
        """创建成功响应"""
        response = APIResponse(
            success=True,
            message=message,
            data=data
        )
        return response.to_json_response(status_code)
    
    @staticmethod  
    def error(message: str = "操作失败", error_code: str = None, 
             status_code: int = 400, data: Any = None):
        """创建错误响应"""
        response = APIResponse(
            success=False,
            message=message,
            error_code=error_code,
            data=data
        )
        return response.to_json_response(status_code)
    
    @staticmethod
    def from_operation_result(operation_result, success_message: str = None, 
                            success_status: int = 200, error_status: int = 400):
        """从OperationResult创建响应"""
        if operation_result.success:
            return ResponseFormatter.success(
                message=success_message or operation_result.message,
                data=operation_result.details,
                status_code=success_status
            )
        else:
            return ResponseFormatter.error(
                message=operation_result.message,
                error_code=operation_result.error,
                status_code=error_status,
                data=operation_result.details
            )